package com.example.springbootsocketserver.socket;

import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint("/websocket/{sid}")
@Component
@Slf4j
public class WebSocketEndPoint {
    private String sid;
    private static final ConcurrentHashMap<String,Session> SESSION_MAP = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.sid = sid;
        SESSION_MAP.put(sid,session);
        log.info("有新的连接：sid:{},session_id:{},当前连接数:{}",sid,session.getId(),SESSION_MAP.size());
        // 处理WebSocket连接建立时的逻辑
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到消息:{},内容:{}",sid,message);
        if ("ping".equals(message)){
            try{
                session.getBasicRemote().sendText("pong");
            }catch (IOException E){
                log.error("onMessage消息推送失败:{},内容:{}",sid,message);
            }
        }else {
            //排除自己
            sendMeasureDataInfoExcludeSelf(message,sid);
        }
        // 处理接收到的WebSocket消息
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        // 处理WebSocket连接关闭时的逻辑
        SESSION_MAP.remove(this.sid);
        log.info("连接关闭，sid:{},session_id:{}!当前连接数:{}",this.sid,session.getId(),SESSION_MAP.size());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        // 处理WebSocket错误时的逻辑
    }

    private void sendMeasureDataInfoExcludeSelf(String message,String sidSelf){
        for (String sid:SESSION_MAP.keySet()){
            if (sidSelf.equals(sid)){
                continue;
            }
            Session session =SESSION_MAP.get(sid);
            try{
                session.getBasicRemote().sendText(message);
            }catch (IOException e){
                log.error("sendMeasureDataInfoExcludeSelf 推送消息失败:{},内容{}",sid,message);
            }
            log.info("sendMeasureDataInfoExcludeSelf 推送消息:{},内容{}",sid,message);
        }

    }
}
